import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QEvent, Qt
from PyQt5.Qt import QPainter, QPoint, QRect


class LabelPro(QtWidgets.QLabel):
    def __init__(self):
        super(LabelPro, self).__init__()
        self.initUI()

        self.img_array = np.zeros((1000, 1000))  # Original ndarray
        self.img_raw = None  # Original QPixmap
        self.img = None  # Resized QPixmap
        self.factor = None  # Label:Original
        self.zero = [0, 0]  # Start Point

    def paintEvent(self, event):
        p = QPainter()
        p.begin(self)
        if self.img: p.drawPixmap(*self.zero, self.img)
        else: p.drawText(QRect(QPoint(0, 0), self.size()), Qt.AlignCenter, self.text())
        p.end()

    def initUI(self):
        self.installEventFilter(self)

    def eventFilter(self, src, event):
        if event.type() == QEvent.Resize and self.img:
           self.PutPixmap(self.img_raw)
        return super().eventFilter(src, event)

    def PutPixmap(self, img):
        """ keep ratio, keep intact """
        self.img_raw = img
        self.resize(img)
        self.update()

    def resize(self, img):
        self.factor = min((self.width() / img.width(), self.height() / img.height()))
        w, h = int(img.width() * self.factor), int(img.height() * self.factor)
        self.zero = [(self.width() - w) // 2, (self.height() - h) // 2]
        self.img = img.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation)

